package com.tql.kingdee.api;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.CommonEntity;
import com.ruoyi.common.redis.service.RedisService;
import com.tql.kingdee.response.*;
import com.tql.kingdee.service.ShopService;
import com.tql.kingdee.util.CommonUtil;
import com.tql.kingdee.response.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class KingdeeService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private ShopService shopService;
    /**
     * 登录金蝶云账户
     * @return
     */
    public String loginKingdeeCloud()
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=  KingdeeServiceApi.logonKingdeeK3Cloud();
            redisService.setCacheObject(CommonUtil.RK_LoginSessionid,loginKingdeeSessionId,CommonUtil.RK_LoginSessionid_timeout, TimeUnit.SECONDS);
        }
        return loginKingdeeSessionId;
    }
    public String reLoginKingdeeCloud()
    {

            String loginKingdeeSessionId=  KingdeeServiceApi.logonKingdeeK3Cloud();
            redisService.setCacheObject(CommonUtil.RK_LoginSessionid,loginKingdeeSessionId,CommonUtil.RK_LoginSessionid_timeout, TimeUnit.SECONDS);

        return loginKingdeeSessionId;
    }

    /**
     *查询机构 主要是店
     * @param approveDate
     * @return
     * {
     *     "parameters": [
     *         {
     *             "FormId": "BD_Department",
     *             "FieldKeys": "fnumber,fname,FParentID.fnumber as parentFnumber,FParentID.fname as parentFname",
     *             "FilterString": "FDocumentStatus='C' and FParentID.fnumber like 'BU1010010002%' and FAUDITDATE>'2020-01-01'",
     *             "StartRow": 0,
     *             "Limit": 100
     *         }
     *     ]
     * }
     */
    public CommonResponse<List<OrgResponse>> getKingdeeOrgBean(String approveDate)
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        CommonResponse<List<OrgResponse>> response= KingdeeServiceApi.getKingdeeOrgBean(loginKingdeeSessionId,approveDate);
        return response;
    }

//    public List<OrgResponse> getAllKingdeeOrgBean(String approveDate,String pFnumber)
//    {
//        List<OrgResponse> alllist=new ArrayList<>();
//        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
//        if(StringUtils.isNull(loginKingdeeSessionId))
//        {
//            loginKingdeeSessionId=loginKingdeeCloud();
//        }
//        for(int i=0;i<10000;i++)
//        {
//            int rowNum=i;
//            CommonResponse<List<OrgResponse>> response= KingdeeServiceApi.getKingdeeOrgBean(loginKingdeeSessionId,approveDate,pFnumber,rowNum);
//            if(0==response.getFlag()) break;
//            if(null==response.getData()||0==response.getData().size()) break;
//            rowNum=i+1000;
//            alllist.addAll(response.getData());
//        }
//
//        return alllist;
//    }

    /**
     * 查询门店下面的部门
     * @param approveDate 审核时间
     * @param parentCode 门店编码
     * @return
     */
    public CommonResponse<List<OrgResponse>> getKingdeeDept(String approveDate,String parentCode)
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        CommonResponse<List<OrgResponse>> response= KingdeeServiceApi.postQueryKingdeeDept(loginKingdeeSessionId,parentCode,approveDate);
        return response;
    }


    public List<CommonEntity> findDeptByParentDeptFnumber(String fnumber) {
        String loginKingdeeSessionId = redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        List<CommonEntity> list1=null;
        CommonResponse<List<OrgResponse>> response= KingdeeServiceApi.postQueryKingdeeDeptForShop(loginKingdeeSessionId,fnumber);
        if(!response.getData().isEmpty())
//            if(response.getErrorInfo().equals("0")))
        {
            List<OrgResponse> list=response.getData();
            if(!CollectionUtils.isEmpty(list)){
                list1= transferList(list);
            }
        }

        return list1;
    }

    private List<CommonEntity> transferList(List<OrgResponse> list) {

      List<CommonEntity> entities=  list.stream().map(each->new CommonEntity(each.getFname(),each.getFnumber())).collect(Collectors.toList());
    return entities;
    }

    /**获得物料集合
     * 查询物料
     * @param approveDate 审核时间
     * @return
     */

    public CommonResponse<List<MaterialResponse>> getMaterial(String approveDate,String stapCode)
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        CommonResponse<List<MaterialResponse>> response= KingdeeServiceApi.postQueryKingdeeMaterial(loginKingdeeSessionId,approveDate,stapCode);
        return response;
    }




    /**
     * request-body
     * {
     *    "parameters": [{
     *         "FormId": "BD_MATERIALUNITCONVERT",
     *         "FieldKeys": "FMaterialId.fnumber,FMaterialId.fname,FConvertDenominator,FCurrentUnitId.FNumber,FCurrentUnitId.FName,FConvertNumerator,FDestUnitId.fnumber,FDestUnitId.fname,FMaterialId.Fspecification",
     *         "FilterString": "FDocumentStatus='C' ",
     *         "StartRow": 0,
     *         "Limit": 10
     *     }]
     * }
     * 查询物料单位换算
     * @param approveDate 审核时间
     * @return
     */

    public CommonResponse<List<MaterialTransUnitResponse>> getMaterialTransUnit(String approveDate,int pageNum)
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        CommonResponse<List<MaterialTransUnitResponse>> response= KingdeeServiceApi.postQueryKingdeeMaterialTransUnit(loginKingdeeSessionId,approveDate,pageNum);
        return response;
    }

    public List<MaterialTransUnitResponse> getMaterialTransUnit(String approveDate) throws  Exception
    {

        List<MaterialTransUnitResponse> list=new ArrayList<>();
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        int rowNum=0;
        for(int i=0;i<10000;i++)
        {
            CommonResponse<List<MaterialTransUnitResponse>> response = KingdeeServiceApi.postQueryKingdeeMaterialTransUnit(loginKingdeeSessionId, approveDate, rowNum);
           if(null!=response.getErrorInfo()&&response.getErrorInfo().getErrorCode().equals("500")&&response.getErrorInfo().getMessage().equals("会话信息已丢失，请重新登录"))
           {
               reLoginKingdeeCloud();
               rowNum=i*1000;
           }
            if(null!=response && 0==response.getFlag()&& null!=response.getData() && response.getData().size()>0)
            {
                rowNum=rowNum+1000;
                list.addAll(response.getData());
            }
            else {
                break;
            }

        }
        return list;
    }


    /**
     * 查询门店收货单
     * @param args
     */

    public List<MaterialPurchaseResponse> getMaterialPurchase(String approveDate, List<String> shops) {
        String loginKingdeeSessionId = redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if (StringUtils.isNull(loginKingdeeSessionId)) {
            loginKingdeeSessionId = loginKingdeeCloud();
        }

        List<MaterialPurchaseResponse> list = new ArrayList<>();
        int rowNum = 0;
        for (int i = 0; i < 99999; i++) {
            CommonResponse<List<MaterialPurchaseResponse>> response = KingdeeServiceApi.postQueryKingdeeMaterialPurchase(loginKingdeeSessionId, approveDate, rowNum, shops);
            if (null != response.getErrorInfo() && response.getErrorInfo().getErrorCode().equals("500") && response.getErrorInfo().getMessage().equals("会话信息已丢失，请重新登录")) {
                reLoginKingdeeCloud();
                rowNum = i * 1000;
            }
            if (null != response && 0 == response.getFlag() && null != response.getData() && response.getData().size() > 0) {
                rowNum = rowNum + 1000;
                list.addAll(response.getData());
            } else {
                break;
            }


        }
        return list;
    }





    /**
     * 查询门店入库单
     * @param args
     */

    public CommonResponse<List<MaterialIncaseResponse>> getMaterialIncase(String approveDate, int pageNum)
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        CommonResponse<List<MaterialIncaseResponse>> response= KingdeeServiceApi.postQueryKingdeeMaterialIncase(loginKingdeeSessionId,approveDate,pageNum,null);
        return response;
    }
    public List<MaterialIncaseResponse> getMaterialIncase(String approveDate,List<String>  depts)
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        List<MaterialIncaseResponse> list = new ArrayList<>();
        int rowNum = 0;
        for (int i = 0; i < 99999; i++) {
            CommonResponse<List<MaterialIncaseResponse>> response = KingdeeServiceApi.postQueryKingdeeMaterialIncase(loginKingdeeSessionId, approveDate, rowNum,depts);
            if (null != response.getErrorInfo() && response.getErrorInfo().getErrorCode().equals("500") && response.getErrorInfo().getMessage().equals("会话信息已丢失，请重新登录")) {
                reLoginKingdeeCloud();
                rowNum = i * 1000;
            }
            if (null != response && 0 == response.getFlag() && null != response.getData() && response.getData().size() > 0) {
                rowNum = rowNum + 1000;
                list.addAll(response.getData());
            } else {
                break;
            }


        }
        return list;
    }











    /**
     * 查询分步式调出单
     * @param args
     */

    public CommonResponse<List<MaterialTransferoutResponse>> getMaterialTransferout(String approveDate, int rowNum)
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        CommonResponse<List<MaterialTransferoutResponse>> response= KingdeeServiceApi.postQueryKingdeeMaterialTransferout(loginKingdeeSessionId,approveDate,rowNum,null);
        return response;
    }
    public List<MaterialTransferoutResponse> getMaterialTransferout(String approveDate,List<String> shops)
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        List<MaterialTransferoutResponse> list = new ArrayList<>();
        int rowNum = 0;
        for (int i = 0; i < 99999; i++) {
            CommonResponse<List<MaterialTransferoutResponse>> response = KingdeeServiceApi.postQueryKingdeeMaterialTransferout(loginKingdeeSessionId, approveDate, rowNum,shops);
            if (null != response.getErrorInfo() && response.getErrorInfo().getErrorCode().equals("500") && response.getErrorInfo().getMessage().equals("会话信息已丢失，请重新登录")) {
                reLoginKingdeeCloud();
                rowNum = i * 1000;
            }
            if (null != response && 0 == response.getFlag() && null != response.getData() && response.getData().size() > 0) {
                rowNum = rowNum + 1000;
                list.addAll(response.getData());
            } else {
                break;
            }


        }
        return list;
    }




    /**
     * 查询分步式调入单
     * @param args
     */

    public CommonResponse<List<MaterialTransferoutResponse>> getMaterialTransferin(String approveDate, int rowNum)
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        CommonResponse<List<MaterialTransferoutResponse>> response= KingdeeServiceApi.postQueryKingdeeMaterialTransferin(loginKingdeeSessionId,approveDate,rowNum,null);
        return response;
    }

    public List<MaterialTransferoutResponse> getMaterialTransferin(String approveDate,List<String> shops)
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        List<MaterialTransferoutResponse> list = new ArrayList<>();
        int rowNum = 0;
        for (int i = 0; i < 99999; i++) {
            CommonResponse<List<MaterialTransferoutResponse>> response = KingdeeServiceApi.postQueryKingdeeMaterialTransferin(loginKingdeeSessionId, approveDate, rowNum,shops);
            if (null != response.getErrorInfo() && response.getErrorInfo().getErrorCode().equals("500") && response.getErrorInfo().getMessage().equals("会话信息已丢失，请重新登录")) {
                reLoginKingdeeCloud();
                rowNum = i * 1000;
            }
            if (null != response && 0 == response.getFlag() && null != response.getData() && response.getData().size() > 0) {
                rowNum = rowNum + 1000;
                list.addAll(response.getData());
            } else {
                break;
            }


        }
        return list;
    }





    /**
     * 查询员工
     * @param args
     */

    public CommonResponse<List<com.ruoyi.system.api.domain.EmpResponse>> getEmp(String approveDate, int pageNum)
    {
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }
        CommonResponse<List<com.ruoyi.system.api.domain.EmpResponse>> response= KingdeeServiceApi.postQueryKingdeeEmp(loginKingdeeSessionId,approveDate,pageNum,null);
        return response;
    }



    public List<com.ruoyi.system.api.domain.EmpResponse> getAllEmp(String approveDate)
    {
        List<com.ruoyi.system.api.domain.EmpResponse> list=new ArrayList<>();
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }

        int rowNum=0;
        for(int i=0;i<10000;i++)
        {
             CommonResponse<List<com.ruoyi.system.api.domain.EmpResponse>> response= KingdeeServiceApi.postQueryKingdeeEmp(loginKingdeeSessionId,approveDate,rowNum,null);
            if(null!=response.getErrorInfo()&&response.getErrorInfo().getErrorCode().equals("500")&&response.getErrorInfo().getMessage().equals("会话信息已丢失，请重新登录"))
            {
                reLoginKingdeeCloud();
                rowNum=i*1000;
            }
            if(null!=response && 0==response.getFlag()&& null!=response.getData() && response.getData().size()>0)
            {
                rowNum=rowNum+1000;
                list.addAll(response.getData());
            }
            else {
                break;
            }

        }
        return list;
    }


    public List<com.ruoyi.system.api.domain.EmpResponse> getEmpByIdCard(String approveDate,String idcard)
    {
        List<com.ruoyi.system.api.domain.EmpResponse> list=new ArrayList<>();
        String loginKingdeeSessionId=redisService.getCacheObject(CommonUtil.RK_LoginSessionid);
        if(StringUtils.isNull(loginKingdeeSessionId))
        {
            loginKingdeeSessionId=loginKingdeeCloud();
        }

        int rowNum=0;
        for(int i=0;i<10000;i++)
        {
            CommonResponse<List<com.ruoyi.system.api.domain.EmpResponse>> response= KingdeeServiceApi.postQueryKingdeeEmp(loginKingdeeSessionId,approveDate,rowNum,idcard);
            if(null!=response.getErrorInfo()&&response.getErrorInfo().getErrorCode().equals("500")&&response.getErrorInfo().getMessage().equals("会话信息已丢失，请重新登录"))
            {
                reLoginKingdeeCloud();
                rowNum=i*1000;
            }
            if(null!=response && 0==response.getFlag()&& null!=response.getData() && response.getData().size()>0)
            {
                rowNum=rowNum+1000;
                list.addAll(response.getData());
            }
            else {
                break;
            }

        }
        return list;
    }














    public static void main(String[] args) {
//        CommonResponse<List<OrgResponse>> response=  new KingdeeService().getKingdeeOrgBean("2023-01-01");
//        List<OrgResponse> list= response.getData();
//        list.forEach(System.out::println);
        //System.out.println(response.toString());
//
//        CommonResponse<List<OrgResponse>> response= new KingdeeService().getKingdeeOrgBean("20230101",null,1);
//        List<OrgResponse> list=response.getData();
//        if(null!=list)
//        for(int i=0;i<1000 ;i++)
//        {
//
//            System.out.println(i);
//            if(i==5) return;
//        }

      //  List<OrgResponse> list=new KingdeeService().getAllKingdeeOrgBean("20230101",null);


    }
    //查询那些门店已经开通了本系统的服务
    public List<String> getEnabledShop() {
        List<String> enabledShops = redisService.getCacheList("enabledShops");
        if (CollectionUtils.isEmpty(enabledShops)) {
            List<String> shops = shopService.getEnabledShop();
            if (CollectionUtils.isEmpty(shops)) return null;
            //redis持久化
            redisService.setCacheList("enabledShops", shops);
            return shops;
        } else {
            return enabledShops;
        }

    }


}
